<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

class Message extends Model
{

    use HasDateTimeFormatter;

    protected $table = 'message';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    public function fromUser()
    {
        return $this->hasOne(User::class, 'id', 'from_user_id');
    }

    public function topic()
    {
        return $this->hasOne(Topic::class, 'id', 'relation_id')->select(['id', 'title']);
    }

    // 返回当前页数据列和总数据量
    public function getPaginate($where = [], $with= [], $select = ['*'], $page = 1, $perPage = 10)
    {

        $data = $this->newQuery()
            ->when($where, function ($query, $where) {
                return $query->where($where);
            })
            ->when($with, function ($query, $with) {
                return $query->with($with);
            })
            ->orderBy('id', 'desc')
            ->paginate($perPage, $select, 'page', $page);

        return ['list' => $data->toArray()['data'], 'total' => $data->total()];
    }

}
